<template>
  <div class="carbon-platform">
    <!-- Preloader -->
    <div class="preloader-wrapper" v-if="isLoading">
      <div class="preloader"></div>
    </div>

    <nav class="navbar sticky-top bg-white shadow-sm py-3">
      <div class="container">
        <div class="d-flex justify-content-between align-items-center w-100">
          <!-- 网站标志 -->
          <div class="navbar-logo">
            <span class="logo-icon">🌱</span>
            <span class="logo-text">绿碳平台</span>
          </div>

          <!-- 中间导航链接 - 桌面版 -->
          <ul class="navbar-nav list-unstyled d-flex flex-row gap-3 gap-lg-5 justify-content-center flex-wrap align-items-center mb-0 fw-bold flex-grow-1 mx-4">
            <li class="nav-item">
              <a href="/index" class="nav-link text-dark hover:text-primary transition-colors">首页</a>
            </li>
            <li class="nav-item">
              <a href="/shop" class="nav-link text-dark hover:text-primary transition-colors">碳积分市场</a>
            </li>
            <li class="nav-item">
              <a href="/blog" class="nav-link text-dark hover:text-primary transition-colors">博客</a>
            </li>
            <li class="nav-item">
              <a href="/contact" class="nav-link text-dark hover:text-primary transition-colors">联系我们</a>
            </li>
            <li class="nav-item">
              <a href="/about" class="nav-link text-dark hover:text-primary transition-colors">关于我们</a>
            </li>
            <li class="nav-item">
              <a href="/order" class="nav-link text-dark hover:text-primary transition-colors">我的订单</a>
            </li>
          </ul>

          <!-- 右侧功能区 - 使用emoji图标 -->
          <div class="d-flex align-items-center gap-4 gap-lg-5">
            <!-- 搜索按钮 -->
            <button class="btn p-2 text-dark hover:text-primary transition-colors" aria-label="搜索">
              <span class="fs-5">🔍</span>
            </button>

            <!-- 购物车 -->
            <a href="/cart" class="btn p-2 text-dark hover:text-primary transition-colors position-relative" aria-label="购物车">
              <span class="fs-5">🛒</span>
<!--              <span class="position-absolute top-0 right-0 btn-success text-white text-xs rounded-full h-5 w-5 flex items-center justify-center" style="border-radius: 50%;">3</span>-->
            </a>

            <!-- 用户菜单 -->
            <div class="dropdown">
              <button class="btn p-2 text-dark hover:text-primary transition-colors" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="用户菜单">
                <span class="fs-5">👤</span>
              </button>
              <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="/login">登录</a></li>
                <li><a class="dropdown-item" href="/register">注册</a></li>
                <li><a class="dropdown-item" href="/account">我的账户</a></li>
              </ul>
            </div>

            <!-- 移动端菜单按钮 -->
            <button class="btn d-lg-none p-2 text-dark" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu" aria-label="菜单">
              <span class="fs-5">☰</span>
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 顶部横幅部分 -->
    <div class="banner-section">
      <div class="container">
        <div class="banner-content">
          <h1 class="banner-title">我的购物车</h1>
        </div>
      </div>
    </div>

    <!-- 主内容区域 - 购物车 -->
    <main class="cart-page py-5">
      <div class="container-lg">
        <div class="row">
          <div class="col-12">
            <!-- 购物车表格和汇总 -->
            <div class="card border-0 shadow-sm mb-4">
              <div class="card-body p-0">
                <!-- 空购物车状态 -->
                <div v-if="cartItems.length === 0" class="text-center py-5">
                  <i class="bi bi-cart-x fs-1 text-muted"></i>
                  <p class="mt-3">您的购物车是空的</p>
                  <router-link to="/shop" class="btn btn-primary mt-3">继续购物</router-link>
                </div>

                <!-- 有商品的状态 -->
                <div v-else class="row g-0">
                  <!-- 商品表格 (占8列) -->
                  <div class="col-lg-8 pe-lg-3">
                    <div class="table-responsive">
                      <table class="table align-middle">
                        <thead class="bg-light">
                        <tr>
                          <th width="100">商品图片</th>
                          <th>商品名称</th>
                          <th width="150">单价</th>
                          <th width="200">数量</th>
                          <th width="150">小计</th>
                          <th width="100">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="item in cartItems" :key="item.cid">
                          <td>
                            <img :src="item.factoryImage || '/images/product-thumb-1.png'" :alt="item.factoryName" width="80" class="img-thumbnail">
                          </td>
                          <td>
                            <h6 class="mb-0">{{ item.factoryName || '碳积分商品' }}</h6>
                            <small class="text-muted">{{ item.factoryDescription || '' }}</small>
                          </td>
                          <td>¥{{ (item.pricePerUnit || 0).toFixed(2) }}</td>
                          <td>
                            <div class="input-group quantity-selector">
                              <input type="number" class="form-control text-center" v-model.number="item.quantity" min="1" @change="validateQuantity(item)">
                            </div>
                          </td>
                          <td class="fw-bold text-danger">¥{{ (item.totalPrice || 0).toFixed(2) }}</td>
                          <td>
                            <button @click="removeItem(item.cid)" class="btn btn-sm btn-outline-danger">
                              <i class="bi bi-trash"></i> 删除
                            </button>
                          </td>
                        </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>

                  <!-- 购物车汇总 (占4列) -->
                  <div class="col-lg-4">
                    <div class="card border-0 shadow-sm h-100">
                      <div class="card-body">
                        <h5 class="card-title mb-4">购物车汇总</h5>
                        <div class="d-flex justify-content-between mb-3">
                          <span>商品合计</span>
                          <span>¥{{ cartSubtotal }}</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                          <span>运费</span>
                          <span v-if="cartSubtotal >= 99" class="text-success">免运费</span>
                          <span v-else>¥10.00</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between fw-bold">
                          <span class="fs-5">应付总额</span>
                          <span class="text-danger fs-5">¥{{ cartTotal }}</span>
                        </div>
                        <div class="d-grid gap-3 mt-4">
                          <p @click="continueShopping" class="btn btn-outline-primary">
                            <i class="bi bi-arrow-left"></i> 继续购物
                          </p>
                          <button @click="checkout" class="btn btn-danger btn-lg">
                            去结算 <i class="bi bi-arrow-right"></i>
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚部分 -->
    <footer class="main-footer">
      <div class="container">
        <div class="footer-bottom">
          <p class="copyright">© 2025 绿碳平台 版权所有 | 京ICP备12345678号</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
import Swiper from 'swiper/bundle'
import 'swiper/swiper-bundle.css'
import { cartApi, orderApi } from '../api/index.js'

export default {
  name: 'CartPage',
  data() {
    return {
      isLoading: false,
      shippingFee: 10,
      cartItems: [],
      currentUserId: null, // 当前用户ID
      activeCategory: null,
      categories: [
        {id: 1, name: '全部商品', image: 'images/all-category.jpg'},
        {id: 2, name: '智能手机', image: 'images/phones-category.jpg'},
        {id: 3, name: '配件周边', image: 'images/accessories-category.jpg'},
        {id: 4, name: '平板电脑', image: 'images/tablets-category.jpg'},
        {id: 5, name: '智能手表', image: 'images/watches-category.jpg'},
        {id: 6, name: '笔记本电脑', image: 'images/laptops-category.jpg'},
        {id: 7, name: '智能家居', image: 'images/smart-home-category.jpg'},
        {id: 8, name: '耳机音响', image: 'images/audio-category.jpg'}
      ],
      relatedSearches: [
        'iPhone 14', 'Galaxy S23', 'AirPods Max', 'iPad Pro',
        'Watch Ultra', 'Buds Live', 'FreeBuds Pro', 'Enco Air'
      ],
      features: [
        {title: '免费配送', icon: '🚚', description: '订单满99元享免费配送服务'},
        {title: '100%安全支付', icon: '🔒', description: '保障您的支付信息安全'},
        {title: '品质保证', icon: '✅', description: '所有商品严格质量把关'},
        {title: '优惠保障', icon: '💰', description: '保证提供最优惠价格'},
        {title: '每日特惠', icon: '🛒', description: '每日更新超值特惠商品'}
      ]
    }
  },
  computed: {
    cartSubtotal() {
      return this.cartItems.reduce((total, item) => {
        return total + parseFloat(item.totalPrice || 0)
      }, 0).toFixed(2)
    },
    cartTotal() {
      const subtotal = parseFloat(this.cartSubtotal)
      const shipping = subtotal >= 99 ? 0 : 10
      return (subtotal + shipping).toFixed(2)
    }
  },
  async mounted() {
    // 获取当前用户ID
    this.getCurrentUserId();
    // 加载购物车数据
    await this.loadCartData();
    this.loadBootstrap()
  },
  methods: {
    // 获取当前用户ID（后端以业务主键 uid 查询）
    getCurrentUserId() {
      const currentUser = localStorage.getItem('currentUser');
      if (currentUser) {
        const userData = JSON.parse(currentUser);
        // 优先使用 uid，其次才回退到 id
        this.currentUserId = userData.uid || userData.id || 1;
      } else {
        this.currentUserId = 1; // 默认 uid=1（便于演示）
      }
    },

    // 加载购物车数据
    async loadCartData() {
      if (!this.currentUserId) return;
      
      this.isLoading = true;
      try {
        const response = await cartApi.getUserCart(this.currentUserId);
        if (response.data && response.data.code === '1') {
          // 后端返回的是CartSummaryDto对象，购物车商品在obj.cartItems中
          this.cartItems = response.data.obj?.cartItems || [];
        } else {
          console.error('加载购物车失败:', response.data?.message);
          this.cartItems = [];
        }
      } catch (error) {
        console.error('加载购物车失败:', error);
        this.cartItems = [];
      } finally {
        this.isLoading = false;
      }
    },

    continueShopping() {
      this.$router.push('/shop');
    },

    loadBootstrap() {
      if (typeof window !== 'undefined') {
        require('bootstrap/dist/js/bootstrap.bundle.min')
      }
    },

    // 更新商品数量
    async updateQuantity(item, newQuantity) {
      if (newQuantity < 1) return;
      
      try {
        const updateData = {
          cid: item.cid,
          quantity: newQuantity
        };
        const response = await cartApi.updateQuantity(updateData);
        if (response.data && response.data.code === '1') {
          item.quantity = newQuantity;
        } else {
          alert('更新数量失败: ' + (response.data?.message || '未知错误'));
        }
      } catch (error) {
        console.error('更新数量失败:', error);
        alert('更新数量失败，请稍后重试');
      }
    },

    validateQuantity(item) {
      if (item.quantity < 1) {
        this.updateQuantity(item, 1);
      } else {
        this.updateQuantity(item, item.quantity);
      }
    },

    // 删除购物车商品
    async removeItem(cid) {
      if (!confirm('确定要删除这个商品吗？')) return;
      
      try {
        const response = await cartApi.deleteCartItem(cid);
        if (response.data && response.data.code === '1') {
          // 从本地数组中移除
          this.cartItems = this.cartItems.filter(item => item.cid !== cid);
          alert('删除成功');
        } else {
          alert('删除失败: ' + (response.data?.message || '未知错误'));
        }
      } catch (error) {
        console.error('删除商品失败:', error);
        alert('删除失败，请稍后重试');
      }
    },

    // 结算 -> 提交订单：按工厂分单，逐单创建并清空购物车
    async checkout() {
      if (this.cartItems.length === 0) {
        alert('购物车为空，请先添加商品');
        return;
      }

      const uid = this.currentUserId;
      if (!uid) {
        alert('未获取到用户，请重新登录');
        return;
      }

      try {
        // 1) 将购物车按 factoryId 分组
        const byFactory = new Map();
        for (const item of this.cartItems) {
          const list = byFactory.get(item.factoryId) || [];
          list.push(item);
          byFactory.set(item.factoryId, list);
        }

        // 2) 逐工厂创建订单
        let successCount = 0;
        for (const [factoryId, items] of byFactory.entries()) {
          const totalQty = items.reduce((sum, it) => sum + (it.quantity || 0), 0);

          // orderItemCreDtos 需要单价与数量
          const orderItemCreDtos = items.map(it => ({
            qty: it.quantity,
            pricePerUnit: it.pricePerUnit || it.currentPricePerUnit || 0
          }));

          const payload = {
            buyerId: uid,            // 后端以 uid 识别买家
            factoryId: factoryId,    // 工厂业务主键 fid
            qtyRequested: totalQty,
            orderItemCreDtos
          };

          const resp = await orderApi.createOrder(payload);
          if (resp.data && resp.data.code === '1') {
            successCount++;
          } else {
            console.error('创建订单失败:', resp.data);
            alert('部分订单创建失败: ' + (resp.data?.message || '未知错误'));
          }
        }

        // 3) 清空购物车（按 uid）并刷新
        try {
          await cartApi.clearCart(uid);
        } catch (e) {
          console.warn('清空购物车失败，可手动刷新:', e);
        }

        if (successCount > 0) {
          alert(`已成功创建 ${successCount} 笔订单`);
          await this.loadCartData();
          this.$router.push('/order');
        }

      } catch (error) {
        console.error('提交订单失败:', error);
        alert('提交订单失败，请稍后重试');
      }
    },

    searchItem(item) {
      alert(`正在搜索: ${item}`);
    }
  },
  watch: {
    '$route'(to, from) {
      if (to.path === '/cart' && from.path !== '/cart') {
        this.loadCartData()
      }
    }
  },
}
</script>

<style scoped>
@import url('https://cdn.bootcdn.net/ajax/libs/Swiper/9.4.1/swiper-bundle.min.css');
@import url('https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css');

.organic-store {
  font-family: 'Nunito', sans-serif;
}

/* Preloader */
.preloader-wrapper {
  position: fixed;
  z-index: 9999;
  background: rgba(255, 255, 255, 0.9);
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preloader {
  width: 50px;
  height: 50px;
  border: 3px solid #0d6efd;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* Banner Section */
.banner-section {
  background-image: url('../../public/images/banner-1.jpg');
  background-size: cover;
  background-position: center;
  height: 300px;
  display: flex;
  align-items: center;
  position: relative;
}

.banner-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.2);
}

.banner-content {
  position: relative;
  z-index: 1;
  color: #fff;
  padding: 20px;
}

.banner-title {
  font-size: 3rem;
  font-weight: 700;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  margin: 0;
}

/* Offcanvas styles */
.offcanvas {
  transition: transform 0.3s ease-in-out;
}

.offcanvas-start {
  width: 280px;
}

.offcanvas-end {
  width: 320px;
}

/* Cart Page Styles */
.cart-page {
  min-height: 40vh;
}

/* Cart Table */
.table th {
  font-weight: 600;
  background-color: #f8f9fa;
}

.table td, .table th {
  vertical-align: middle;
}

.img-thumbnail {
  width: 80px;
  height: 80px;
  object-fit: contain;
  padding: 0.25rem;
  background-color: #fff;
  border: 1px solid #dee2e6;
  border-radius: 0.25rem;
}

/* Quantity Selector */
.quantity-selector {
  max-width: 50px;
}

.quantity-selector .btn {
  width: 38px;
  padding: 0.375rem 0;
}

.quantity-selector input {
  width: 50px;
  text-align: center;
  padding: 0.375rem;
}


/* Related Searches */
.related-searches {
  background-color: #f8f9fa;
}

.section-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: #333;
}

.feature-icon {
  font-size: 2rem;
  margin-bottom: 15px;
}

/* Footer */
.footer {
  background-color: #212529;
  color: #fff;
}

.footer a {
  color: #adb5bd;
  transition: color 0.3s ease;
  text-decoration: none;
}

.footer a:hover {
  color: #fff !important;
}

.footer .form-control {
  background-color: #2c3e50;
  border-color: #2c3e50;
  color: #fff;
}

.footer .form-control:focus {
  background-color: #2c3e50;
  color: #fff;
  box-shadow: none;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
  .banner-section {
    height: 200px;
  }

  .banner-title {
    font-size: 2rem;
  }

  .table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

  .quantity-selector {
    max-width: 120px;
  }
}

@media (max-width: 576px) {
  .banner-title {
    font-size: 1.5rem;
  }

  .img-thumbnail {
    width: 60px;
    height: 60px;
  }
}

/* Utility Classes */
.text-primary {
  color: #0d6efd !important;
}

.bg-primary {
  background-color: #0d6efd !important;
}

.btn-primary {
  background-color: #0d6efd;
  border-color: #0d6efd;
}

.btn-primary:hover {
  background-color: #0b5ed7;
  border-color: #0a58ca;
}

.btn-danger {
  background-color: #dc3545;
  border-color: #dc3545;
}

.btn-danger:hover {
  background-color: #bb2d3b;
  border-color: #b02a37;
}

.btn-outline-danger {
  color: #dc3545;
  border-color: #dc3545;
}

.btn-outline-danger:hover {
  background-color: #dc3545;
  color: #fff;
}

.text-danger {
  color: #dc3545 !important;
}

.text-success {
  color: #198754 !important;
}

.text-muted {
  color: #6c757d !important;
}

.rounded-pill {
  border-radius: 50rem !important;
}

.shadow-sm {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075) !important;
}

/* 新增样式 */
.cart-page .table-responsive {
  padding: 1rem;
}

.cart-page .card.h-100 {
  border-radius: 0 0.375rem 0.375rem 0;
}
/* 在全局CSS或组件样式中添加 */
.related-searches {
  background-color: var(--bg-section) !important;
  padding: 1rem;
  border-radius: 8px;
}

.search-tag {
  display: inline-block;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  text-decoration: none;
  font-size: 0.875rem;
  background-color: var(--tag-bg);
  color: var(--tag-text);
  border: 1px solid var(--tag-border);
  transition: all 0.2s ease;
}

.search-tag:hover {
  background-color: var(--tag-hover);
  color: var(--tag-text);
}

@media (max-width: 992px) {
  .cart-page .col-lg-8 {
    padding-right: 0 !important;
  }

  .cart-page .col-lg-4 {
    padding-top: 1.5rem;
  }

  .cart-page .card.h-100 {
    border-radius: 0 0 0.375rem 0.375rem;
  }
}

</style>